package cn.xieyang.gen.wrk;

import cn.hutool.core.io.FileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ShangtouRefreshLocalDataBaseByDev {

    public static void main(String[] args) {
        // 导出配置
        String exportHost = "47.103.56.190";
        int exportPort = 50008;
        String exportUser = "root";
        String exportPassword = "K41MOcbbSe#U";
        String exportPath = "/data/";

        // 导入配置
        String importUser = "root";
        String importPassword = "123456";
        String importPath = "/data/";

        String[] outputDatabases = {"collection", "collection_public", "collection_zworkflow"};
        String[] importDatabases = {"collection", "collection_public", "collection_workflow"};
        clearDatabase(importDatabases);

        List<String> asList = Arrays.asList(outputDatabases);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < asList.size(); i++) {
            String outputDatabase = asList.get(i);
            String importDatabase = importDatabases[i];
            String exportAbsolutePath = exportPath + outputDatabase + ".sql";
            FileUtil.del(exportAbsolutePath);
            Thread thread = new Thread(() -> {
                // 执行导出
                exportDatabases(exportHost, exportPort, exportUser, exportPassword, exportAbsolutePath, new String[]{outputDatabase});
                // 执行导入
                importDatabases(importUser, importPassword, importPath + outputDatabase + ".sql", new String[]{importDatabase});
            });
            thread.start();
            threadList.add(thread);
        }
        threadList.stream().forEach(item->{
            try {
                item.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
    }

    private static void exportDatabases(String host, int port, String user, String password, String outputPath, String[] databases) {
        for (String db : databases) {
            try {
                ProcessBuilder processBuilder = new ProcessBuilder(
                        "mysqldump",
                        "-h", host,
                        "-P", String.valueOf(port),
                        "-u", user,
                        "--password=" + password,  // 密码特殊字符需要处理
                        "--result-file=" + outputPath,
                        db
                );

                Process process = processBuilder.start();
                int exitCode = process.waitFor();

                if (exitCode == 0) {
                    System.out.println("导出成功: " + db);
                } else {
                    printError(process);
                    System.out.println("导出失败: " + db);
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void importDatabases(String user, String password, String inputPath, String[] databases) {
        for (String db : databases) {
            File sqlFile = new File(inputPath);
            if (!sqlFile.exists()) {
                System.out.println("SQL文件不存在: " + sqlFile.getPath());
                continue;
            }

            try {
                ProcessBuilder processBuilder = new ProcessBuilder(
                        "mysql",
                        "-u", user,
                        "--password=" + password,
                        db
                ).redirectInput(sqlFile);

                Process process = processBuilder.start();
                int exitCode = process.waitFor();

                if (exitCode == 0) {
                    System.out.println("导入成功: " + db);
                } else {
                    printError(process);
                    System.out.println("导入失败: " + db);
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void printError(Process process) throws IOException {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getErrorStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.err.println(line);
            }
        }
    }

    private static void clearDatabase(String[] importDatabases) {
        // 连接 URL 不指定具体数据库，通过参数传递用户名和密码
        String url = "jdbc:mysql://localhost:3306/?user=root&password=123456&useSSL=false";

        try (Connection conn = DriverManager.getConnection(url);
             Statement stmt = conn.createStatement()) {

            for (String importDatabase : importDatabases) {
                // 删除数据库（建议添加 IF EXISTS 避免报错）
                stmt.executeUpdate("DROP DATABASE IF EXISTS " + importDatabase + "");

                // 创建数据库并指定字符集
                stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + importDatabase + " CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
            }

            System.out.println("数据库操作成功");
        } catch (SQLException e) {
            System.err.println("操作失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

}
